/* Copyright (c) 2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.p091;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.lucky_byte.pay.jar.JdbcTable;
import com.lucky_byte.pay.jar.Runtime;

/**
 * POS 009.1 接入服务模块
 */
public class Main
{
	private static final Logger logger = LogManager.getLogger();

	static private PoolListener listener = null;
	static private Thread listener_thread = null;

	static void addNetAddress(NetworkInterface neti,
			List<Object> address) throws SocketException {
		Enumeration<InetAddress> inetAddresses = neti.getInetAddresses();
		for (InetAddress inetAddress : Collections.list(inetAddresses)) {
			address.add(inetAddress.getHostAddress());
		}
	}

	public static void main(String[] args) {
		if (Runtime.basePath() == null) {
			return;
		}
		Runtime.setNotifySender("POS 009.1 服务");

		// 退出时清理
		java.lang.Runtime.getRuntime().addShutdownHook(
				new Thread(new Runnable() {
					public void run() {
						logger.info("POS 009.1 接入服务开始退出...");
						if (listener != null) {
							listener.stop();
						}
						if (listener_thread != null) {
							listener_thread.interrupt();
						}
					}
				}));

		// 查询本机所有的 IP 地址，用于匹配主机中的配置
		List<Object> address_list = new ArrayList<>();
		try {
			Enumeration<NetworkInterface> netis =
					NetworkInterface.getNetworkInterfaces();
			for (NetworkInterface i : Collections.list(netis)) {
				if (i.isLoopback()) {
					continue;
				}
				addNetAddress(i, address_list);
			}
		} catch (Exception e) {
			logger.error("查询本地网络地址错误[{}]", e.getMessage());
			return;
		}
		StringBuilder ipaddrs = new StringBuilder();
		ipaddrs.append("ipaddr_priv in (");
		for (int i = 0; i < address_list.size(); i++) {
			ipaddrs.append("?");
			if (i < address_list.size() - 1) {
				ipaddrs.append(",");
			}
		}
		ipaddrs.append(")");
		JdbcTable table = JdbcTable.listBy_NE("pay_hosts",
				ipaddrs.toString(), address_list);
		if (table == null || table.getRecordCount() == 0) {
			logger.error("主机 {} 没有配置 POS 009.1 接入服务.", address_list);
			return;
		}
		listener = new PoolListener(table.getRecord(0));
		listener_thread = new Thread(listener);
		listener_thread.start();
	}

}
